package com.neuedu.service.impl;

import com.neuedu.service.FileUploadService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.username}")
    private String username;
    @Value("${minio.password}")
    private String password;
    @Override
    public String upload(MultipartFile file, String bucket) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        // 为了防止文件到服务器上覆盖，所以上传的时候需要把文件重命名来保证文件名的唯一性
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        // 获取文件后缀名
        String suffix = FilenameUtils.getExtension(file.getOriginalFilename());
        String fileName = String.format("%s.%s", time, suffix);
        MinioClient client = MinioClient.builder()
                .endpoint(endpoint)
                .credentials(username, password)
                .build();
        PutObjectArgs args = PutObjectArgs.builder()
                .contentType(file.getContentType())
                .object(fileName)
                .stream(file.getInputStream(), file.getSize(), 0)
                .bucket(bucket)
                .build();
        client.putObject(args);
        return String.format("/%s/%s", bucket, fileName);
    }
}
